package com.powernode.driver.service.impl;


import com.powernode.common.execption.PowerException;
import com.powernode.common.result.ResultCodeEnum;
import com.powernode.driver.properties.TencentProperties;
import com.powernode.driver.service.CiService;
import com.powernode.driver.service.CosService;
import com.powernode.model.vo.driver.CosUploadVo;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.GeneratePresignedUrlRequest;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.StorageClass;
import com.qcloud.cos.region.Region;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CosServiceImpl implements CosService {

    @Resource
    private TencentProperties tencentProperties;

    @Resource
    private CiService ciService;


    /**
     * 配送员上传文件 身份证照片
     *
     * @param file 文件
     * @param path 文件存储的路径
     */
    @Override
    public CosUploadVo upload(MultipartFile file, String path) {
        COSClient cosClient = getCosClient();

        //构建对象元数据
        ObjectMetadata objectMetadata = new ObjectMetadata();
        //文件大小
        objectMetadata.setContentLength(file.getSize());
        //文件类型 .png  .jpeg
        objectMetadata.setContentType(file.getContentType());
        objectMetadata.setContentEncoding("utf-8");

        //拼接上传路径和文件名 要修改上传的文件名 lyf.png
        //获取文件后缀名
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        //拼接上传路径和文件名
        String uploadPath = "/driver/" + path + "/" + UUID.randomUUID().toString().replaceAll("-", "") + fileType;


        try {
            //向cos发送上传请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(tencentProperties.getBucketPrivate(), uploadPath, file.getInputStream(), objectMetadata);
            putObjectRequest.setStorageClass(StorageClass.Standard);

            //上传文件
            cosClient.putObject(putObjectRequest);
            //释放资源
            cosClient.shutdown();


            //图片审核
            Boolean flag = ciService.imageAuditing(uploadPath);

            if (!flag) {
                //删除图片
                cosClient.deleteObject(tencentProperties.getBucketPrivate(), uploadPath);
               throw new PowerException(ResultCodeEnum.IMAGE_AUDITION_FAIL);
            }


            CosUploadVo cosUploadVo = new CosUploadVo();
            //文件在cos中存储的路径
            cosUploadVo.setUrl(uploadPath);

            //文件在cos中显示的访问地址
            String imageUrl = getImageUrl(path);
            cosUploadVo.setShowUrl(imageUrl);

            return cosUploadVo;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


    /**
     * 获取cos中图片的查看地址
     */
    @Override
    public String getImageUrl(String path) {
        COSClient cosClient = getCosClient();

        //构建请求对象
        GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(tencentProperties.getBucketPrivate(), path, HttpMethodName.GET);

        //设置url有效期
        Date expiration = new DateTime().plusMinutes(20).toDate();
        urlRequest.setExpiration(expiration);

        //发送请求获取url
        URL url = cosClient.generatePresignedUrl(urlRequest);

        cosClient.shutdown();

        System.out.println("image url:" + url);

        return url.toString();
    }


    /**
     * 获取cos客户端
     */
    private COSClient getCosClient() {
        //创建凭证
        COSCredentials cred = new BasicCOSCredentials(tencentProperties.getSecretId(), tencentProperties.getSecretKey());

        //创建区域
        Region region = new Region(tencentProperties.getRegion());

        //创建client配置对象
        ClientConfig clientConfig = new ClientConfig(region);

        // 这里建议设置使用 https 协议
        // 从 5.6.54 版本开始，默认使用了 https
        clientConfig.setHttpProtocol(HttpProtocol.https);

        //创建客户端
        COSClient cosClient = new COSClient(cred, clientConfig);


        return cosClient;
    }


}
